#include "FYT2021.h"

int FYT2021()
{
    /* SerialPort */
#ifdef Windows
    SerialPort serial_port("COM1");
#elif defined Linux
    SerialPort serial_port("/dev/ttyTHS2");
#endif
    if (!serial_port.Init()) {
        printf("Serial_port initialization failed.\n");
        return 1;
   }
    else{
        printf("Serial_port initialization success.\n");
    }
    Protocol protocol(serial_port);
    
    //接受下位机数据
    std::thread receive(&Protocol::receiveData, protocol);

    /* Video source */
    cameraParam.LoadParam();
    FightingCapture* capture;
    if (cameraParam.camera_type == "MindVision")
        capture = new FightingMVCapture();
    else if (cameraParam.camera_type == "Daheng")
        capture = new FightingDahengCapture();
    else if (cameraParam.camera_type == "USB")
        capture = new FightingUSBCapture(stoi(cameraParam.camera_name));
    else if (cameraParam.camera_type == "Video")
        capture = new FightingVideoCapture(cameraParam.camera_name);
    else {
        printf("Invalid Camera Type: %s.\n", cameraParam.camera_type.c_str());
        return 1;
    }
    printf("Camera name: %s\n", cameraParam.camera_name.c_str());
    if (capture && !capture->init()) {
        printf("Video source initialization failed.\n");
        delete capture;
        return 1;
    }
    printf("camera init success\n");

    /* ArmorDetector and RuneDetector */
    armorParam.LoadParam();
    runeParam.LoadParam();
    ArmorDetector armor_detector;
    RuneDetector rune_detector;
    
    cv::Mat src;
    cv::Point3f target;

    ///* Video writer */
    //time_t currentTime = std::time(NULL);
    //char chCurrentTime[64];
    //std::strftime(chCurrentTime, sizeof(chCurrentTime), "%Y%m%d%H%M", std::localtime(&currentTime));
    //std::string stCurrentTime = chCurrentTime;
    //// cv::VideoWriter video_writer(stCurrentTime + ".avi", 0, 210, cv::Size(1280, 1024), true);

    while (true) {
        if (capture->read(src)) {
            if (!((mcu_data.state == State::ARMOR_STATE && armor_detector.DetectArmor(src, target))
                    || (mcu_data.state == State::RUNE_STATE && rune_detector.DetectRune(src, target))))
                target = { 0, 0, -1 };
            protocol.sendTarget(target);
           //cv::imshow("src", src);
           //cv::waitKey(0);
           // video_writer.write(src);
        } else
            break;
    }
    delete capture;
    return 0;
}

int main(int argc, char* argv[])
{
    while (true) {
        FYT2021();
        printf("### Error, start again! ###\n\n");
        cv::waitKey(2000);
    }
    return 0;
}
